<script setup lang="ts">
import { ADDRESS, ADDRESS_MAP, URL_CONFIGS } from '@/constants'

const panelPosition = { bottom: 32, height: 28, width: 400, right: 5 }
const mapColor = ref('rgba(255, 0, 0, 0.8)')
const optionSelected = ref('成都市行政区划面')
const transparent = ref(100)
const options = [
  {
    value: '成都市行政区划面标注',
    label: '成都市行政区划面标注'
  },
  {
    value: '成都市行政区划面outlie',
    label: '成都市行政区划面outlie'
  },
  {
    value: '成都市行政区划面',
    label: '成都市行政区划面'
  }
]
const input = ref('')
const restaurants = ref<{ value: string }[]>(ADDRESS)
const querySearch = (queryString: string, cb: any) => {
  const results = queryString ? restaurants.value.filter(createFilter(queryString)) : restaurants.value
  // call callback function to return suggestions
  cb(results)
}
function createFilter(queryString: string) {
  return (restaurant: { value: string }) => restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
}

function changeTransparent() {
  const hasMVT = hasVecterTileLayer()
  if (!hasMVT) return
  switch (optionSelected.value) {
    case '成都市行政区划面标注':
      map.setPaintProperty('chengdu@SiChuan#2(0_24)', 'text-opacity', transparent.value / 100)
      map.setPaintProperty('chengdu@SiChuan#2(0_24)', 'icon-opacity', transparent.value / 100)
      break
    case '成都市行政区划面outlie':
      map.setPaintProperty('chengdu@SiChuan#1_unique__outline(0_24)', 'line-opacity', transparent.value / 100)
      break
    case '成都市行政区划面':
      map.setPaintProperty('chengdu@SiChuan#1_unique_(0_24)', 'fill-opacity', transparent.value / 100)
      break
    default:
      map.setPaintProperty('chengdu@SiChuan#1_unique_(0_24)', 'fill-opacity', transparent.value / 100)
      break
  }
}

function filterMVTMap() {
  const hasMVT = hasVecterTileLayer()
  if (!hasMVT) return
  // 根据城市名找出 id
  const index = ADDRESS_MAP.findIndex((city) => city === input.value)
  if (index !== -1) {
    map.setFilter('chengdu@SiChuan#2(0_24)', ['in', '$id', index + 1])
    map.setFilter('chengdu@SiChuan#1_unique__outline(0_24)', ['in', '$id', index + 1])
    map.setFilter('chengdu@SiChuan#1_unique_(0_24)', ['in', '$id', index + 1])
  } else {
    map.setFilter('chengdu@SiChuan#2(0_24)', null)
    map.setFilter('chengdu@SiChuan#1_unique__outline(0_24)', null)
    map.setFilter('chengdu@SiChuan#1_unique_(0_24)', null)
  }
}

function resetLayerSetting() {
  transparent.value = 100
  const hasMVT = hasVecterTileLayer()
  if (!hasMVT) return
  map.listLayers().forEach((item: any) => {
    if (item.startsWith('chengdu@SiChuan')) map.removeLayer(item)
  })
  map.removeSource('chengdu')
  if (map.getLayer('highlight-feature-layer')) map.removeLayer('highlight-feature-layer')
  if (map.getStyle('highlight-feature-source')) map.removeSource('highlight-feature-source')
  map.addStyle(URL_CONFIGS.CHENGDU_MAP_URL)
  setTimeout(() => {
    queueMicrotask(() => {
      map.addSource('highlight-feature-source', {
        type: 'geojson',
        data: {
          type: 'FeatureCollection',
          features: [] // 初始为空
        }
      })
      map.addLayer({
        id: 'highlight-feature-layer',
        type: 'fill',
        source: 'highlight-feature-source',
        paint: {
          'fill-color': '#FF0000', // 高亮颜色
          'fill-opacity': 0.8 // 高亮透明度
        }
      })
    })
  }, 1000)
}

function changeLayerStyle() {
  const hasMVT = hasVecterTileLayer()
  if (!hasMVT) return
  switch (optionSelected.value) {
    case '成都市行政区划面标注':
      map.setPaintProperty('chengdu@SiChuan#2(0_24)', 'text-color', mapColor.value)
      break
    case '成都市行政区划面outlie':
      map.setPaintProperty('chengdu@SiChuan#1_unique__outline(0_24)', 'line-color', mapColor.value)
      break
    case '成都市行政区划面':
      map.setPaintProperty('chengdu@SiChuan#1_unique_(0_24)', 'fill-pattern', null)
      map.setPaintProperty('chengdu@SiChuan#1_unique_(0_24)', 'fill-color', mapColor.value)
      break
    default:
      map.setPaintProperty('chengdu@SiChuan#1_unique_(0_24)', 'fill-color', mapColor.value)
      break
  }
}

function hideLayer() {
  const hasMVT = hasVecterTileLayer()
  if (!hasMVT) return
  let selectedLayer: any = null
  switch (optionSelected.value) {
    case '成都市行政区划面标注':
      selectedLayer = map.getLayer('chengdu@SiChuan#2(0_24)')
      break
    case '成都市行政区划面outlie':
      selectedLayer = map.getLayer('chengdu@SiChuan#1_unique__outline(0_24)')
      break
    case '成都市行政区划面':
      selectedLayer = map.getLayer('chengdu@SiChuan#1_unique_(0_24)')
      break
    default:
      selectedLayer = map.getLayer('chengdu@SiChuan#1_unique_(0_24)')
      break
  }
  if (map.getLayoutProperty(selectedLayer.id, 'visibility') === 'visible') {
    map.setLayoutProperty(selectedLayer.id, 'visibility', 'none')
  } else {
    map.setLayoutProperty(selectedLayer.id, 'visibility', 'visible')
  }
}

function hasVecterTileLayer(): boolean {
  const layers = ['chengdu@SiChuan#2(0_24)', 'chengdu@SiChuan#1_unique__outline(0_24)', 'chengdu@SiChuan#1_unique_(0_24)']
  if (layers.every((layer) => map.getLayer(layer))) {
    return true
  } else {
    ElMessage.error('请先加载成都矢量瓦片地图！')
    return false
  }
}
</script>

<template>
  <WidgetPanel :title="'矢量瓦片'" :position="panelPosition">
    <template #header></template>
    <div class="mvt-container">
      <div class="mvtlayer-selecter">
        <p>图层选择：</p>
        <el-select v-model="optionSelected" class="m-2" placeholder="图层选择" size="small" style="width: 165px">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-button color="#2B333E" size="small" @click="resetLayerSetting">重置图层设置</el-button>
      </div>
      <div class="color-selecter">
        <span>图层颜色风格:</span>
        <el-color-picker class="color-picker" v-model="mapColor" show-alpha />
        <el-button color="#2B333E" size="small" @click="changeLayerStyle">修改风格</el-button>
        <el-button color="#2B333E" size="small" @click="hideLayer">图层显隐</el-button>
      </div>
      <el-container>
        <el-header style="height: 5px; margin-top: 20px">地图透明度(%)：</el-header>
        <el-main>
          <div>
            <el-slider v-model="transparent" show-input size="small" :min="0" :max="100" :step="1" @change="changeTransparent" />
          </div>
        </el-main>
      </el-container>
      <div class="mvt-query">
        <span>属性过滤:</span>
        <el-autocomplete v-model="input" :fetch-suggestions="querySearch" :trigger-on-focus="false" clearable style="width: 300px" placeholder="区县名称" />
        <el-button color="#2B333E" @click="filterMVTMap">过滤</el-button>
      </div>
    </div>
  </WidgetPanel>
</template>

<style lang="scss" scoped>
.mvt-container {
  display: flex;
  flex-direction: column;
  color: #ccc;

  .color-selecter {
    margin-top: 20px;
    margin-left: 20px;
    span {
      margin-right: 20px;
    }
    :deep(.el-color-picker) {
      margin-right: 20px;
    }
  }

  .mvtlayer-selecter {
    display: flex;
    margin-left: 20px;
  }

  .mvt-query {
    display: flex;
    align-items: center;
    margin-left: 20px;

    span {
      width: 100px;
      margin-right: 10px;
    }
  }
}
</style>
